#!/bin/bash


function download_python(){
    curl -O https://www.python.org/ftp/python/3.7.6/Python-3.7.6.tgz
}

function build_python(){
    tar -zxvf Python-3.7.6.tgz
    cd Python-3.7.6
    mkdir build
    cd build
    ../configure --prefix=/usr/local/python37 --enable-shared
    make -j8
    make install
    cp libpython3.7m.so.1.0 /usr/lib64 
    #cp /home/cloudguan/.local/bashboot/vim /usr/bin/vim
    cd ../../
}

function pre_check(){
    if [ -d /usr/local/python37 ]
    then
        rm -rf /usr/local/python37
    fi

    if [ ! -f ./yum ]
    then
        curl https://gitee.com/CloudGuan/bashboot/raw/master/yum >> yum
        chmod 771 yum
    fi 

    if [ ! -f ./urlgrabber-ext-down ]
    then
        curl https://gitee.com/CloudGuan/bashboot/raw/master/urlgrabber-ext-down >> urlgrabber-ext-down
    fi 
}

function after_check(){
    #处理好 python3 环境变量 和 软连接
    pypath=`which python`
    if [ $? -eq 0  ]
    then
        # bak python
        Sp=${pypath%/*}
        mv $pypath $Sp/python_bak
    fi

    if [ ! -f /bin/python3 ]
    then
        ln -s /usr/local/python37/bin/python3 /bin/python3
    fi 

    ln -s /usr/local/python37/bin/python3 /usr/bin/python 
    ln -s /usr/local/python37/bin/pip3 /usr/bin/pip
    ln -s /usr/local/python37/bin/pip3 /usr/bin/pip3

    #替换yum 和
    cp ./yum /usr/bin/yum
    cp ./urlgrabber-ext-down /usr/libexec/urlgrabber-ext-down  
}

function yum_op(){
    yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel
    yum install libffi-devel -y
    yum install -y python-devel
}

#如果安装了python3 脚本退出
if [ -x "$(command -v python3)" ]; then
    echo "检测到已经安装python3 退出安装"
    exit 0
fi

yum_op

if [ ! -f Python-3.7.6.tgz ]
then
    download_python
    if [ $? -gt 0 ];then
        echo "下载python 错误请手动下载!"
        exit 1
    fi 
fi

pre_check

build_python

after_check

echo "安装完成Python 完成 开始清理！！"
rm -rf Python-3.7.6
rm -f Python-3.7.6.tgz urlgrabber-ext-down yum